package com.example.foodapp.util;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyOkhttpUtil {
    private static MyOkhttpUtil myOkhttpUtil;
    private static OkHttpClient client;
    private static MediaType type;
    private String urltop = "http://192.168.137.199:8080" ;

    public static void MyOkhttpUtil(){
        client = new OkHttpClient();
        type = MediaType.parse("application/x-www-form-urlencoded");
    }
    public static MyOkhttpUtil getMyOkHttpUtil(){
        if (myOkhttpUtil == null) myOkhttpUtil = new MyOkhttpUtil();
        return myOkhttpUtil;
    }
    public String getData(String url,String body){
        RequestBody requestBody = RequestBody.create(type,body);
        Request request=new Request.Builder()
            .url(urltop+url)
            .post(requestBody)
            .build();
        String data = null;
        try {
            Response response = client.newCall(request).execute();
            data = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            data = "请求失败";
        }
        return data;
    }

//    public String postData(String url,String body) throws IOException {
//        RequestBody requestBody = RequestBody.create(type,body);
//        Request request = new Request.Builder()
//                .url(url)
//                .post(requestBody)
//                .build();
//        Response response = client.newCall(request).execute();
//        String data = response.body().string();
//        return data;
//    }


}
//    RequestBody body=RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),"");
//    Request request=new Request.Builder()
//            .url("http://192.168.137.199:8080/foodserver/food/list")
//            .post(body)
//            .build();
//
//    OkHttpClient client =new OkHttpClient();
//                try {
//                        Response response=client.newCall(request).execute();
//                        returns=response.body().string();
//                        //将字符串转成JSON
//                        JSONArray jsonArray=new JSONObject(returns).getJSONArray("data");
//                        Log.e("SAD",jsonArray.toString());
//                        for (int i=0;i>jsonArray.length();i++){
//                        JSONObject jsonObject=jsonArray.getJSONObject(i);
//                        Food food=new Food();
//                        food.setName(jsonObject.getString("name"));
//                        food.setLabel(jsonObject.getString("label"));
//                        food.setPrice(jsonObject.getInt("price"));
//                        list.add(food);
//                        }
//                        } catch (Exception e) {
//                        e.printStackTrace();
//                        }